<script setup lang="ts">
import { ref } from 'vue';
import { onMounted } from 'vue';
import { showLoadingToast,closeToast,showToast,showConfirmDialog } from 'vant';
import type {ActionSheetAction} from 'vant'
import {request} from '../api/index'
import b64toBlob from 'b64-to-blob';

const isShowAvatorSheet = ref(false)
const isShowChangeNameSheet = ref(false)

const nickName = ref('昵称')

const profile = ref<GeekUser>({} as GeekUser)
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  try{
    const res = await request.get<GeekResponse<GeekUser>>('v1_0/user/profile')
        profile.value = res.data.data
  }catch(e){
    console.log(e)
  }finally{
    closeToast()
  }


  
})

const showDialog =()=>{
  showConfirmDialog({
  title: '温馨提示',
  message:
    '亲，您确认要退出吗？',
})
  .then(() => {
    // on confirm
    loginOut()
  })
  .catch(() => {
    // on cancel
  });
} 

const onSelectAvatar =  async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
     // 拍照上传
        // 拍照上传
    const data = await geek.pickerCamera()
    await onUpdateAvatar(data)

  } else if (i === 1) {
       // 相册上传
       console.log('相册上传');
       const data = await geek.pickerPhoto()
    await onUpdateAvatar(data)
  }
}

const loginOut= ()=>{
    geek.loginOut()
}

const onUpdateAvatar = async (data: string) => {
  try {
    isShowAvatorSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = b64toBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('photo', image, Date.now() + '.jpeg')
    const res = await request.patch<GeekResponse<{ id:String,photo: string }>>('v1_0/user/photo', fd)
    profile.value.photo = URL.createObjectURL(image)
    const user = geek.queryUser()
    user.photo = res.data.data.photo
    geek.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    console.log(err)
    showToast({ message: '上传失败' })
  }
}

const onChangeName=async()=>{
  profile.value.name = nickName.value
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  try{
    const res = await request.patch<GeekResponse<GeekUser>>('v1_0/user/profile',profile.value)
     
  }catch(e){
    console.log(e)
  }finally{
    closeToast()
    isShowChangeNameSheet.value = false
  }
}

const onclickNickName = ()=>{
  nickName.value = profile.value.name
  isShowChangeNameSheet.value = true
}

const onClickLeft=()=>{
  geek.back()
}

</script>

<template>
    <div class="profile-edit-page">

<van-nav-bar
  title="个人信息"
  left-arrow
  @click-left="onClickLeft"
></van-nav-bar>

 <van-cell-group>
            <van-cell @click="isShowAvatorSheet = true" title="头像">
                  <template #right-icon>
                     <van-icon class="avator-icon" :name="profile.photo" ></van-icon>
                   </template>
            </van-cell>
            <van-cell title="昵称" is-link :value="profile.name" @click="onclickNickName"/>
            <van-cell title="简介" is-link :value="profile.intro" />
</van-cell-group>

<van-cell-group>
            <van-cell title="性别" is-link :value="profile.gender==1?'男':'女'" />
            <van-cell title="生日" is-link :value="profile.birthday" />

    <div class="submit" @click="showDialog">
        退出登录
    </div>
</van-cell-group>
<van-action-sheet v-model:show="isShowAvatorSheet" :actions="[{ name: '拍照' }, { name: '本地选择' }]"
      @select="onSelectAvatar" cancel-text="取消" :style="{ paddingBottom: '20px' }">
</van-action-sheet>

<van-popup
  v-model:show="isShowChangeNameSheet"
  position="bottom"
  :style="{ height: '100%' }"
>
<van-nav-bar
  title="编辑昵称"
  @click-left="isShowChangeNameSheet=false"
  left-arrow
  right-text="提交"
  @click-right="onChangeName"
></van-nav-bar>
<van-cell-group inset>
  <van-field v-model="nickName" label="昵称" placeholder="请输入用户名" ></van-field>
</van-cell-group>
</van-popup>


 </div>
</template>

<style lang="css" scoped>
.profile-edit-page {
  height: '100%';
  width: '100%';
  padding: 20;
  background-color: #f00;
}
.avator-icon {
    font-size: 16px;
    line-height: inherit;
  }
  .submit {
    text-align: center; 
    color: #f00;
  padding: 16px;
}
</style>